package logic

import (
	"context"
	"encoding/json"
	"fmt"
	"home-sys/cache"
	"home-sys/moder"
	"time"

	"home-sys/homerpc/homerpc"
	"home-sys/homerpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type UserShowLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUserShowLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserShowLogic {
	return &UserShowLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *UserShowLogic) UserShow(in *homerpc.UserShowRequest) (*homerpc.UserShowResponse, error) {
	// todo: add your logic here and delete this line
	var user moder.User
	key := fmt.Sprintf("user_%d", in.UserId)

	result, _ := cache.Rdb.Get(l.ctx, key).Result()

	if result == "" {
		err := user.UserShow(moder.DB, in.UserId)
		if err != nil {
			return nil, err
		}
		marshal, _ := json.Marshal(user)
		cache.Rdb.Set(l.ctx, key, marshal, time.Minute*30)
	} else {
		json.Unmarshal([]byte(result), &user)
	}

	return &homerpc.UserShowResponse{
		Username: user.Username,
		Password: user.Password,
		UserId:   int64(user.ID),
	}, nil
}
